package org.finesys.gateway.configure;

import org.finesys.gateway.handler.GlobalExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.ArrayList;
import java.util.List;

@Configuration(proxyBeanMethods = false)
public class GatewayConfiguration {
    /**
     * 异常对象声明
     */
    @Bean
    public GlobalExceptionHandler globalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

    /**
     * 跨域处理
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        List<String> allow = new ArrayList<>();
        allow.add("*");
        corsConfiguration.setAllowedMethods(allow);
        corsConfiguration.setAllowedHeaders(allow);
        corsConfiguration.setAllowedOriginPatterns(allow);
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(86400L);//seconds=1day
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(urlBasedCorsConfigurationSource);
    }
}
